package com.ukao.cashregister.printer;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gprinter.command.EscCommand;
import com.gprinterio.GpDevice;
import com.ukao.cashregister.R;
import com.ukao.cashregister.bean.BatchlTabBean;
import com.ukao.cashregister.bean.ReceiptBean;
import com.ukao.cashregister.bean.StringBean;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.MyDateUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.utils.Utils;

import java.util.List;
import java.util.Vector;

//import static com.tencent.bugly.crashreport.crash.c.n;
import static com.ukao.cashregister.R.id.sendModeText;

/**
 * 打印小票
 */

public class PrinterReceipt {
    private int lengter = cutoff().length() - 7;
    private static PrinterReceipt mPrinterHelper;
    private Vector<Byte> Command;


    public static PrinterReceipt getInstance() {
        if (mPrinterHelper == null) {
            mPrinterHelper = new PrinterReceipt();
        }
        return mPrinterHelper;
    }


    /**
     * 打印小票
     *
     * @param printInfo
     * @param mDevice
     */
    public void printGp80(ReceiptBean printInfo, GpDevice mDevice) {
        mDevice.openUSBPort(Utils.getContext());

        if (mDevice == null) {
            System.out.println("usbDevice is null");
            return;
        }

        try {


            EscCommand esc = new EscCommand();
            //设置字体
            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_2, EscCommand.HEIGHT_ZOOM.MUL_2);
            //设置居中
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            //打印字体
            esc.addText(printInfo.getMercName() + "\n");
            if (!CheckUtils.isEmpty(printInfo.getStoreName())){
                esc.addText(printInfo.getStoreName() + "\n\n");
            }
            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_1, EscCommand.HEIGHT_ZOOM.MUL_1);

            if (!CheckUtils.isEmpty(printInfo.getCabinetOrderNo())) {
                esc.addText(printInfo.getCabinetOrderNo() + "\n");
            }
            if (!CheckUtils.isEmpty(printInfo.getCabinetName())) {
                esc.addText(printInfo.getCabinetName() + "\n");
            }

            esc.addText(printInfo.getOrderNo() + "\n");


            //设置条形码高度  60   240
            esc.addSetBarcodeHeight((byte) 120);
            //设置条形码宽度
            esc.addSetBarcodeWidth((byte) 2);

            //打印条形码

            esc.addCODE128(esc.genCodeB(printInfo.getOrderNo()));

            //生成二维码，第一个参数为要生成的文本，第二个参数为生成尺寸，第三个参数为生成回调
            esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);
            List<ReceiptBean.OrderProductListBean> mProductList = printInfo.getOrderProductList();
            String cloCount = printInfo.getClothCnt() + printInfo.getAnnexCnt();
            esc.addText(Align("入库 :" + MyDateUtils.formatDateCustom(printInfo.getRecoredTime(), "MM-dd HH:mm:ss"),cloCount) + " \n");
            String sendModeText = printInfo.getSendModeText();
            if (printInfo.getSendMode() == 2 && !CheckUtils.isEmpty(printInfo.getSendWorkName())) {
                sendModeText = sendModeText + ":" + printInfo.getSendWorkName();

            }
            if (!CheckUtils.isEmpty(sendModeText)) {
                esc.addText(sendModeText + "\n");
            }

            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            esc.addText(cutoffs() + "\n");
            esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);


            if (!CheckUtils.isEmpty(mProductList)) {
                Gson mGson = new Gson();

                for (int j = 0; j < mProductList.size(); j++) {

                    ReceiptBean.OrderProductListBean orderProductListBean = mProductList.get(j);
                    String color = "";
                    if (!CheckUtils.isEmpty(orderProductListBean.getColorDesc())) {  /*/*瑕疵*/
                        List<StringBean> mColorDesclist = mGson.fromJson(orderProductListBean.getColorDesc(),
                                new TypeToken<List<StringBean>>() {
                                }.getType());
                        StringBuffer mColorBuffer1 = new StringBuffer();
                        for (int i = 0; i < mColorDesclist.size(); i++) {
                            if (i != mColorDesclist.size() - 1) {
                                mColorBuffer1.append(mColorDesclist.get(i).getName() + "/");
                            } else {
                                mColorBuffer1.append(mColorDesclist.get(i).getName());
                            }


                        }
                        color = mColorBuffer1.toString();
                    }

                    String strflawDesc = "";
                    if (!CheckUtils.isEmpty(orderProductListBean.getFlawDesc())) {  /*/*瑕疵*/
                        List<StringBean> mflawDesclist = mGson.fromJson(orderProductListBean.getFlawDesc(),
                                new TypeToken<List<StringBean>>() {
                                }.getType());
                        StringBuffer mflawBuffer = new StringBuffer();
                        for (int i = 0; i < mflawDesclist.size(); i++) {
                            if (i != mflawDesclist.size() - 1) {
                                mflawBuffer.append(mflawDesclist.get(i).getName() + "/");
                            } else {
                                mflawBuffer.append(mflawDesclist.get(i).getName());
                            }
                        }
                        strflawDesc = mflawBuffer.toString();
                    }


                    esc.addText(Align(orderProductListBean.getProductName() + "  " + orderProductListBean.getScanCode(), "￥" + CheckUtils.isEmptyNumber(orderProductListBean.getSubtotal()) + "\n"));/**/
                    //金额*百分比和输出线
                    esc.addText(Align("￥"+CheckUtils.isEmptyNumber(orderProductListBean.getServiceAmt())+"*"+orderProductListBean.getDiscount()+"%",orderProductListBean.getTranTypeStr()+" "+orderProductListBean.getTranNum()+"\n"));

                    if (!CheckUtils.isEmpty(color)&&!CheckUtils.isEmpty(strflawDesc)) {
                        color = color + "/"+strflawDesc;
                    }else if(!CheckUtils.isEmpty(strflawDesc)){
                        color+=strflawDesc;
                    }
                    if(color.length()>20){
                        color=color.substring(0,20);
                        color+="...";
                        esc.addText(color + "\n"); /*颜色*/
                    }else if(!CheckUtils.isEmpty(color)){
                        esc.addText(color + "\n"); /*颜色*/
                    }
                    if (j == mProductList.size() - 1) {
                        //esc.addText(cutoffs());
                    } else {
                        // esc.addText(cutoff());
                    }
                }
            }
            esc.addSelectJustification(EscCommand.JUSTIFICATION.RIGHT);
            if (!CheckUtils.isNull(printInfo.getOrderPrice())) {/*合计金额 */
                esc.addText("衣物总额：" + CheckUtils.isEmptyNumber(printInfo.getOrderPrice()) + "\n");
            }
            if (!CheckUtils.isNull(printInfo.getCouponAmt()) && printInfo.getCouponAmt() != 0) {/*优惠卷 */
                esc.addText("优惠卷：" + CheckUtils.isEmptyNumber(printInfo.getCouponAmt()) + "\n");
            }
            if (printInfo.getIsModifyPrice()) {
                esc.addText("修改金额：" + CheckUtils.isEmptyNumber(printInfo.getModifyPrice()) + "\n");
            }
            int takesEndFee = printInfo.getSendCarriage() + printInfo.getTakeCarriage();
            if (takesEndFee != 0) {
                String takesEndFees = CheckUtils.isEmptyNumber(takesEndFee);
                esc.addText("取送费：" + takesEndFees + "\n");
            }
            if (printInfo.getPayStatus()) {/* 已支付金额*/
                esc.addText("已付金额：" + CheckUtils.isEmptyNumber(printInfo.getPaidPrice()) + "\n");
            }


            esc.addText("付款状态：" + printInfo.getPayStatusText() + "\n");
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            esc.addText(cutoff());
            esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);

            String remark = printInfo.getUserRemark();
            if (!CheckUtils.isEmpty(remark)) {
                esc.addText("客户备注：" + remark + "\n");

            } else {
                esc.addText("客户备注：无" + "\n");
            }
            esc.addText(cutoff());
            String userName = "";
            if (!CheckUtils.isEmpty(printInfo.getUserName())) {
                userName = "  " + printInfo.getUserName();
            }
            if (!CheckUtils.isEmpty(printInfo.getUserPhone())) {
                userName = printInfo.getUserPhone() + userName;
            }
            Log.d("卡号", "printGp80: "+printInfo.getUserCardNo());
            esc.addText("客户：" + userName + "\n");
            //判断卡号
            if(!CheckUtils.isEmpty(printInfo.getRfidNo())){
                esc.addText("卡号：" + printInfo.getRfidNo() + "\n");
            }else if(!CheckUtils.isEmpty(printInfo.getUserCardNo())){
                esc.addText("卡号：" + printInfo.getUserCardNo() + "\n");
            }
            String discount = "";
            if (printInfo.getDiscountType()) {
                discount = "多折扣";
            } else {
                discount = printInfo.getDiscount() + "%";
            }
            esc.addText("折扣：" + discount + "  余额：￥" + CheckUtils.isEmptyNumber(printInfo.getUserBalance()) + "\n");
            if (!CheckUtils.isEmpty(printInfo.getTakeAddress())) {
                esc.addText(printInfo.getTakeAddress() + "\n");
            }
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            esc.addText(cutoff());
            esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);
            if (!CheckUtils.isEmpty(printInfo.getWxCode())) {
                esc.addText("微信号：" + printInfo.getWxCode() + "\n");
            }
            if (!CheckUtils.isEmpty(printInfo.getServiceTel())) {
                esc.addText("客服电话：" + printInfo.getServiceTel() + "\n");
            }

            esc.addText("打印时间：" + MyDateUtils.getDateTime() + "\n");


            //切纸和切纸长度


            esc.addCutAndFeedPaper((byte) 20);
            Vector<Byte> Command = new Vector<Byte>(4096, 1024);
            Command = esc.getCommand();
            if (mDevice.isDeviceOpen()) {
                mDevice.sendDataImmediately(Command);
            } else {
                T.show("小票打印机USB连接失败，请重新拔插");
            }
        } catch (Exception ex) {
            T.show(Utils.getContext().getString(R.string.printer_error));
        }


    }


    /**
     * 下票打印机
     *
     * @return
     */
    //分割线
    public String cutoff() {
        StringBuffer mStringBuffer = new StringBuffer();
        String cutline = "-----------------------------------------------";
        return mStringBuffer.append(cutline + "\n").toString();

    }

    public String cutoffs() {
        StringBuffer mStringBuffer = new StringBuffer();
        String cutline = "_______________________________________________";

        return mStringBuffer.append(cutline + "\n").toString();
    }

    //对齐函数（用于一行打印信息一边左对齐一边右对齐）
    public String Align(String left, String right) {
        String str = left + right;
        while (str.length() < 37) {
            left = left + " ";
            str = left + right;
        }
        return str;
    }


    /**
     * 打印批号
     *
     * @param printInfo
     */
    public void printGpBatch(final BatchlTabBean.ListBean printInfo, final int count, final GpDevice mDevice) {
        mDevice.openUSBPort(Utils.getContext());
        if (mDevice == null) {
            System.out.println("usbDevice is null");
            return;
        }

        try {
            EscCommand esc = new EscCommand();
            //设置字体

            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_2, EscCommand.HEIGHT_ZOOM.MUL_2);
            //设置居中
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            //打印字体
            esc.addText("入厂袋号：" + printInfo.getCode() + "\n");
            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_1, EscCommand.HEIGHT_ZOOM.MUL_1);

            esc.addPrintAndFeedLines((byte) 1);
            esc.addText("创建时间：" + MyDateUtils.formatDataTime(printInfo.getCreateTime()) + "\n");
            esc.addPrintAndFeedLines((byte) 1);
            esc.addText("请扫码核对确认" + "\n");
            esc.addPrintAndFeedLines((byte) 1);
//            //设置条形码高度
            esc.addSetBarcodeHeight((byte) 120);
            // 设置条形码宽度
            esc.addSetBarcodeWidth((byte) 3);
            //打印条形码
            //   esc.addRastBitImage(bitmap, bitmap.getWidth(), 0); // 打印图片

            esc.addCODE128(esc.genCodeB(printInfo.getCode()));
            L.i("printInfo.getCode()=" + printInfo.getCode());
            esc.addPrintAndFeedLines((byte) 2);
            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_2, EscCommand.HEIGHT_ZOOM.MUL_2);
            int size = printInfo.getProductCnt() + printInfo.getAnnexCnt();
            esc.addText("共" + size + "件");
            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_1, EscCommand.HEIGHT_ZOOM.MUL_1);
            esc.addPrintAndFeedLines((byte) 3);
            esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);
            String msg = "衣服" + printInfo.getProductCnt() + "件，附件" + printInfo.getAnnexCnt() + "件";
            esc.addText("确认签收：   " + msg + "\n");
            esc.addPrintAndFeedLines((byte) 1);
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            esc.addText(cutoffs());
            esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);
            esc.addPrintAndFeedLines((byte) 2);
            esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);

            if (!CheckUtils.isNull(printInfo.getStoreName())) {
                esc.addText(printInfo.getStoreName() + "\n");
            }

            esc.addText("地址：" + CheckUtils.isEmptyString(printInfo.getStoreRegionalDesc()) + " " + CheckUtils.isEmptyString(printInfo.getStoreAddrDesc()) + "\n");
            esc.addText("打印时间：" + MyDateUtils.getDateTime() + "\n");
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            esc.addText(cutoff());
            esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);


            //切纸和切纸长度
            esc.addCutAndFeedPaper((byte) 20);
            Command = new Vector<Byte>(3096, 1024);
            Command = esc.getCommand();
            mDevice.sendDataImmediately(Command);

            if (count == 0) {
                printGpBatch(printInfo, 1, mDevice);
            }


        } catch (Exception ex) {
            T.show(Utils.getContext().getString(R.string.printer_error));
        }


    }


}
